#include "serversocket.h"

#pragma warning(disable:4996)

CServerSocket::CServerSocket()
{
    m_bInit = false;
    m_ListenSocket = -1;
}

CServerSocket::~CServerSocket()
{
    if (m_ListenSocket != -1) {
        ::closesocket(m_ListenSocket);
    }

    if (m_bInit) {
        ::WSACleanup();
    }
}

bool CServerSocket::DoInit()
{
    WORD wVersionRequested = MAKEWORD(2, 2);
    WSADATA wsaData;
    int err = ::WSAStartup(wVersionRequested, &wsaData);
    if (err != 0) {
        return false;
    }

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {
        return false;
    }
    m_bInit = true;

    m_ListenSocket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (m_ListenSocket == -1) {
        return false;
    }
    printf("listen socket[%lld]\n", m_ListenSocket);

    return true;
}

bool CServerSocket::DoBind(const char* ip, short port)
{
    SOCKADDR_IN addrSrv;
    memset(&addrSrv, 0, sizeof(SOCKADDR_IN));
    addrSrv.sin_addr.S_un.S_addr = inet_addr(ip);//htonl(INADDR_ANY);
    addrSrv.sin_family = AF_INET;
    addrSrv.sin_port = htons(port);
    if (::bind(m_ListenSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)) == -1) {
        int error = WSAGetLastError();
        printf("bind error[%d]\n", error);
        return false;
    }

    return true;
}

bool CServerSocket::DoListen(int backlog)
{
    if (::listen(m_ListenSocket, backlog) == -1) {
        return false;
    }

    return true;
}

bool CServerSocket::DoAccept()
{
    SOCKADDR_IN addrClient;
    int len = sizeof(SOCKADDR);
    char msg[] = "HelloWorld";
    while (true) {
        SOCKET sockClient = ::accept(m_ListenSocket, (SOCKADDR*)&addrClient, &len);
        if (sockClient == -1) {
            break;
        }

        ::send(sockClient, msg, (int)strlen(msg), 0);
        ::closesocket(sockClient);
    }

    return false;
}